import * as joi from 'joi'
import { parameter, get, controller, summary, tag, ENUM_PARAM_IN } from 'koa-joi-swagger-ts'
import kjsRouter from '../util/swagger'
import { logs } from '../util/log'
import Router from '@koa/router'

import userService from '../service/user'
@controller('/v3/db-svr')
class BaseController {
  @get('/')
  index() {
    return false
  }
}

const controllerFun = async (controller: (ctx: Router.RouterContext) => void, ctx: Router.RouterContext, next: () => void, summary: string): Promise<void> => {
  console.log(`${ctx.request.method} ${ctx.request.url}`)
  try {
    await controller(ctx)
    next()
  } catch (e) {
    // console.log(e, `Error while executing '${summary}'`)
    logs.appLog.error(e, `Error while executing '${summary}'`)
  }
}

@controller('/user')
class UserController extends BaseController {
  // const TEST_USER_ID = '5f7025e3bf1ed3ac10a19895'
  @tag('数据库查询')
  @summary('rest风格-查询用户id')
  @get('/{userId}')
  @parameter('userId', joi.string().min(2).description('用户id'), ENUM_PARAM_IN.path)
  async getUser(ctx: Router.RouterContext) {
    ctx.set('Content-Type', 'application/json')
    ctx.set('charset', 'UTF-8')
    // controllerFun统一处理
    // const data = await userService.getUserById(ctx.params.userId)
    // ctx.body = JSON.stringify(data)
    // 自行处理
    try {
      const data = await userService.getUserById(ctx.params.userId)
      ctx.body = JSON.stringify(data)
    } catch (error) {
      ctx.status = 400
      ctx.body = error
    }
  }
}

kjsRouter.loadController(UserController, controllerFun)

export default kjsRouter